package com.elawlink.controller;

import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.elawlink.es.Article;
import com.elawlink.es.ArticleRepository;
 
/**
 * @Author : wuyongde
 * @CreateTime : 2021/5/27
 * @Description :
 **/
@RestController
@RequestMapping("/es")
public class EsController {
 
    @Autowired
    ArticleRepository articleRepository; 
 
    @GetMapping("/add")
    public String add() {
    	System.out.println("es添加测试");
    	
    	Article article = new Article();
    	article.setId(10l);
    	article.setContent("Article article");
    	article.setTitle("威龙测一下");
    	articleRepository.save(article);
		
        return "success";
		
    }
    
    @GetMapping("/delete")
    public String delete() {
    	System.out.println("es删除测试");
    	
    	articleRepository.deleteById(10l);
		
        return "success";
		
    }

    @GetMapping("/update")
    public String update() {
    	System.out.println("es修改测试");
    	
    	Article article = new Article();
    	article.setId(10l);
    	article.setContent("Article article-更新");
    	article.setTitle("威龙测一下-更新");
    	articleRepository.save(article);
		
        return "success";
		
    }
    
    
    @GetMapping("/query")
    public Object query(@RequestParam(value = "title", required = true) String title) {
    	System.out.println("es查询测试》"+title);
        return articleRepository.findByTitle(title);
		
    }
 
    
    @GetMapping("/queryMatch")
    public Object queryMatch(@RequestParam(value = "title", required = true) String title) {
    	System.out.println("es高级查询测试》"+title);
    	
    	MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", title);
    	SearchQuery searchQuery = new NativeSearchQuery(queryBuilder).setPageable(PageRequest.of(0,100));
    	Page<Article> page = (Page<Article>) articleRepository.search(queryBuilder);
    	
        return page;
		
    }
    
}